package com.tm.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.tm.mapper.PersonMapper;
import com.tm.model.Person;
import com.tm.service.PersonService;
import com.tm.vo.PersonVo;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PersonServiceImpl implements PersonService {
    @Resource
    private PersonMapper personMapper;

    //导出
    @Override
    public void allPOIPerson(HttpServletResponse response) {
        List<Person> person = personMapper.selectList(null);
        String fileName = "C:\\Users\\Administrator\\Desktop\\用户信息.xlsx";
        EasyExcel.write(fileName, Person.class).sheet().doWrite(person);

    }
    @Override
    public void uploadFile(MultipartFile dataFile) {
        ArrayList<Person> people = new ArrayList<>();
        try {
            InputStream inputStream = dataFile.getInputStream();
            EasyExcel.read(inputStream, Person.class, new AnalysisEventListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {
                    people.add((Person)o);
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    System.out.println("读取成功");
                }
            }).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        people.forEach(person -> {
            personMapper.insert(person);
        });
    }
    @Override
    public void addPerson(Person person) {
        personMapper.insert(person);
    }

    //s删除·
    @Override
    public void deletePersonId(Integer personId) {
        personMapper.deleteById(personId);
    }

    //修改
    @Override
    public void updatePerson(Person person) {
        personMapper.updateById(person);
    }

    //回显
    @Override
    public Person queryPersonById(Integer personId) {
        return personMapper.queryPersonById(personId);
    }
    //查询
    @Override
    public PersonVo queryPerson(PersonVo personVo) {
        //查询总条数
        Integer  count  = personMapper.queryPersonCount(personVo);
        //将总条数赋值给工具类
        personVo.setTotalCount(count);
        //上一步结束，得到分页的条件和所有条件查询，
        List<Person> list = personMapper.queryPerson(personVo);
        personVo.setList(list);
        return personVo;
    }
}
